package com.example.demo.controller.rmw;

import com.example.demo.util.HttpClientUtils;
import org.springframework.util.CollectionUtils;
import software.amazon.awssdk.auth.credentials.AwsBasicCredentials;
import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.s3.S3Client;
import software.amazon.awssdk.services.s3.S3Configuration;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.*;
import java.util.stream.Collectors;

import software.amazon.awssdk.services.s3.model.GetBucketPolicyRequest;
import software.amazon.awssdk.services.s3.model.PutBucketPolicyRequest;
import software.amazon.awssdk.services.s3.model.DeleteBucketPolicyRequest;
import software.amazon.awssdk.services.s3.model.S3Exception;

import static com.example.demo.util.TestTryCatch.test;


public class TianyiCloudS3Demo {
    private static final String ENDPOINT = "https://huabei-2.zos.ctyun.cn"; // 天翼云 endpoint
    private static final String ACCESS_KEY = "597TPSH9P92HGHDVAMMY";
    private static final String SECRET_KEY = "UvsQnXTbC7jKkfcBzlQ1q9Ccry5LUfXJFLM2QszR";
    private static final String BUCKET_NAME = "bucket-meizi";

    // 初始化天翼云 S3 客户端
    private static S3Client createS3Client() {
        return S3Client.builder()
                .endpointOverride(URI.create(ENDPOINT))
                .region(Region.of("cn-beijing")) // 天翼云使用默认区域
                .credentialsProvider(StaticCredentialsProvider.create(
                        AwsBasicCredentials.create(ACCESS_KEY, SECRET_KEY)
                ))
                .serviceConfiguration(S3Configuration.builder()
                        .pathStyleAccessEnabled(true) // 必须启用路径风格
                        .build())
                .build();
    }

    public static String getDefaultPassword(String memberName) {
        if (memberName.length() >= 2) {
            return memberName.substring(0, 2) + "gs9527";
        }
        return memberName.substring(0, 1) + "gs9527";
    }



    // 在 Bucket Policy 中添加规则，禁止访问指定文件
    public static void blockFileAccess(String objectKey) {
        try (S3Client s3Client = createS3Client()) {
            // 读取现有策略（避免覆盖原有规则）
            String currentPolicy = s3Client.getBucketPolicy(GetBucketPolicyRequest.builder()
                    .bucket(BUCKET_NAME)
                    .build()).policy();

            // 构建新策略（追加拒绝规则）
            String newPolicy = String.format(
                    "{" +
                            "  \"Version\": \"2012-10-17\"," +
                            "  \"Statement\": [%s," +  // 保留原有规则
                            "    {" +
                            "      \"Effect\": \"Deny\"," +
                            "      \"Principal\": \"*\"," +
                            "      \"Action\": \"s3:GetObject\"," + // 禁止读取文件
                            "      \"Resource\": \"arn:aws:s3:::%s/%s\"" + // 指定文件路径
                            "    }" +
                            "  ]" +
                            "}",
                            currentPolicy.isEmpty() ? "" : currentPolicy.replaceFirst("^\\{\"Version\":.*\"Statement\":\\[", ""),
                            BUCKET_NAME, objectKey
            );
//            String newPolicy = "{\n" +
//                    "  \"Version\":  \"2008-10-17\",\n" +
//                    "  \"Statement\":  [\n" +
//                    "    {\n" +
//                    "      \"Sid\":  \"AllowPublicRead\",\n" +
//                    "      \"Effect\":  \"Deny\",\n" +
//                    "      \"Principal\":  {\n" +
//                    "        \"AWS\":  \"*\"\n" +
//                    "      },\n" +
//                    "      \"Action\":  [\n" +
//                    "        \"s3:GetObject\"\n" +
//                    "      ],\n" +
//                    "      \"Resource\":  [\n" +
//                    "        \"arn:aws:s3:::bucket-meizi/"+objectKey+"\"\n" +
//                    "      ]\n" +
//                    "    }\n" +
//                    "  ]\n" +
//                    "}";


            // 更新策略
            s3Client.putBucketPolicy(PutBucketPolicyRequest.builder()
                    .bucket(BUCKET_NAME)
                    .policy(newPolicy)
                    .build());
            System.out.println("[成功] 已禁止访问文件 " + objectKey);
        } catch (S3Exception e) {
            System.err.println("策略更新失败: " + e.getMessage());
        }
    }

    // 从 Bucket Policy 中删除针对文件的拒绝规则
    public static void unblockFileAccess(String objectKey) {
        try (S3Client s3Client = createS3Client()) {
            // 读取当前策略
            String currentPolicy = s3Client.getBucketPolicy(GetBucketPolicyRequest.builder()
                    .bucket(BUCKET_NAME)
                    .build()).policy();

            // 删除匹配的拒绝规则
            String targetResource = String.format("arn:aws:s3:::%s/%s", BUCKET_NAME, objectKey);
            String newPolicy = currentPolicy.replaceAll(
                    "\\{\\s*\"Effect\":\\s*\"Deny\".*?\"Resource\":\\s*\"" + targetResource + "\".*?\\},?", ""
            );

            // 更新策略
            s3Client.putBucketPolicy(PutBucketPolicyRequest.builder()
                    .bucket(BUCKET_NAME)
                    .policy(newPolicy)
                    .build());
            System.out.println("[成功] 已恢复文件 " + objectKey + " 的访问");
        } catch (S3Exception e) {
            System.err.println("策略更新失败: " + e.getMessage());
        }
    }

    public static double convert(double input) {
        // 分离整数部分和小数部分
        long integerPart = (long) input;
        double fractionalPart = input - integerPart;

        // 处理浮点数精度问题
        fractionalPart = Math.round(fractionalPart * 100000.0) / 100000.0;

        if (fractionalPart == 0.0) {
            // 整数或小数部分为0的情况
            return integerPart;
        } else {
            // 有小数部分的情况（无论小数部分大小）
            return integerPart + 0.5;
        }
    }

    public static Date addDate(Date beginDate, int num, int field) {
        Calendar cal = Calendar.getInstance();
        cal.setTime(beginDate);
        cal.add(field, num);
        return cal.getTime();
    }

    private static void test111(int a) {
        for (int i = 0; i < 100; i++) {
            if (i ==1) {
                a =555;
            }
            int b =a;
            System.out.println(b);
        }
    }
    public static void main(String[] args) throws URISyntaxException {
//        String beforeDate = DateUtils.dateToString(DateUtils.addDate(new Date(), -1, DateUtils.MONTH), DateUtils.DEFAULT_DATE_FORMAT);

//            System.out.println("a:"+a);
//            System.out.println( i);
//        System.out.println(convert(3.8));
//        System.out.println(addDate(new Date(), -2, Calendar.DAY_OF_MONTH));

        List<Long> ids = new ArrayList<>();
        ids.add(1750751551417336L);
        ids.add(1750750863051335L);
        ids.add(1750664751965146L);
        ids.add(1750664518252145L);
        ids.add(1750664464583144L);
        ids.add(1750664421659143L);
        ids.add(1750664384316142L);
        ids.add(1750664339418141L);
        ids.add(1750664245879140L);
            ids.add(1750663996757139L);
            ids.add(1750389105171326L);
            ids.add(1750213221896341L);
            ids.add(1749541882644131L);
//            ids.add(1744853293734370L);
//            ids.add(1744790049648291L);
    //        ids.add(1744597052123010L);
    //        ids.add(1744363100029023L);
    //        ids.add(1744362667256025L);
    //        ids.add(1744360165889291L);
    //        ids.add(1744337670554041L);


        String idsParam = ids.stream()
                .map(Object::toString)
                .collect(Collectors.joining("&ids="));
        String getCanStartFlowInfoUrl = "http://vlivetest.peopleurl.cn/cloud/open/activity/api/getActivity?ids="+idsParam;
//        String resp = HttpClientUtils.doGet(getCanStartFlowInfoUrl);
//        System.out.println(resp);
    }

}